/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
 */

package pl.droidsonroids.gif.transforms;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.PixelMapShader;
import ohos.agp.render.Shader;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.Rect;
import ohos.media.image.PixelMap;
import pl.droidsonroids.gif.utils.RectFloatHarmony;

/**
 * {@link Transform} which adds rounded corners.
 */

public class CornerRadiusTransform implements Transform {
    private float mCornerRadius;
    private Shader mShader;
    private final RectFloatHarmony mDstRectF = new RectFloatHarmony();

    /**
     * CornerRadiusTransform
     *
     * @param cornerRadius corner radius, may be 0.
     */
    public CornerRadiusTransform(float cornerRadius) {
        setCornerRadiusSafely(cornerRadius);
    }

    /**
     * Sets the corner radius to be applied when drawing the bitmap.
     *
     * @param cornerRadius corner radius or 0 to remove rounding
     */
    public void setCornerRadius(float cornerRadius) {
        setCornerRadiusSafely(cornerRadius);
    }

    private void setCornerRadiusSafely(float cornerRadius) {
        cornerRadius = Math.max(0, cornerRadius);
        if (cornerRadius != mCornerRadius) {
            mCornerRadius = cornerRadius;
            mShader = null;
        }
    }

    /**
     * getCornerRadius
     *
     * @return The corner radius applied when drawing this drawable. 0 when drawable is not rounded.
     */
    public float getCornerRadius() {
        return mCornerRadius;
    }

    /**
     * Returns current transform bounds - latest received by {@link #onBoundsChange(Rect)}.
     *
     * @return current transform bounds
     */
    public RectFloatHarmony getBounds() {
        return mDstRectF;
    }

    @Override
    public void onBoundsChange(Rect bounds) {
        mDstRectF.set(bounds);
        mShader = null;
    }

    @Override
    public void onDraw(Canvas canvas, Paint paint, PixelMap buffer) {
        if (mCornerRadius == 0) {
            canvas.drawPixelMapHolder(new PixelMapHolder(buffer),mDstRectF.left,mDstRectF.top,paint);
            return;
        }
        if (mShader == null) {
            mShader = new PixelMapShader(new PixelMapHolder(buffer), Shader.TileMode.CLAMP_TILEMODE,
                    Shader.TileMode.CLAMP_TILEMODE);
            final Matrix shaderMatrix = new Matrix();
            shaderMatrix.translate(mDstRectF.left, mDstRectF.top);

            shaderMatrix.scale(mDstRectF.width() / buffer.getImageInfo().size.width, mDstRectF.height()
                    / buffer.getImageInfo().size.height);

            /* mShader.setLocalMatrix(shaderMatrix);*/
        }
        paint.setShader(mShader, Paint.ShaderType.PIXELMAP_SHADER);
        canvas.drawRoundRect(mDstRectF, mCornerRadius, mCornerRadius, paint);
    }
}
